package com.e3.web.core.server;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Properties;

import com.e3.core.utils.ConfigFileReader;


/**
 * 从rpcservlet.properties中读取对应服务的实现类名，并实例化。
 * @author Administrator
 *
 */
public final class GwtRPCActionConfig {
	
	private static boolean isInit = false;
	
	private static Properties props;
	
	private static String propFile = "rpcservlet.properties";
	
	//cache the servlet object to reduce the call count of Class.forname method.
	private static HashMap<String, GwtRPCAction> servlets = new HashMap<String, GwtRPCAction>();
	
	public static void init(){
		if(isInit){
			return;
		}
		String file = ConfigFileReader.getConfigFile(propFile);
		props = new Properties();
		try {
			props.load(new FileInputStream(new File(file)));
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}

	public static GwtRPCAction getRPCServletClass(String serviceName) throws RuntimeException{
		init();
		if(props == null){
			throw new RuntimeException("can't find the service "+serviceName+",probably fail to initiate service servlet config.");
		}
		GwtRPCAction servlet = servlets.get(serviceName);
		if(servlet!=null){
			return servlet;
		}
		String serviceClass = props.getProperty(serviceName);
		try {
			servlet = (GwtRPCAction)Class.forName(serviceClass).newInstance();
			servlets.put(serviceName, servlet);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("can't find the service "+serviceName+" in config file.");
		} 
		return servlet;
	}
}
